package xmltest;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class TestTryWrite {

    public static void main(String[] args) throws IOException {
        //1.创建一个文档对象
        Document document = DocumentHelper.createDocument();
        //2.添加根元素标签
        Element games = document.addElement("games");
        //3.添加子标签，添加game标签
        Element game1 = games.addElement("game");
        //添加属性
        game1.addAttribute("id", "1");
        //添加孙子标签
        Element name = game1.addElement("name");
        name.addText("LOL");
        //添加孙子标签
        game1.addElement("company").addText("Tencent");
        //4.添加第二个game标签
        Element game2 = games.addElement("game");
        //添加属性
        game2.addAttribute("id", "2");
        //添加孙子标签
        game2.addElement("name").addText("DNF");
        //添加孙子标签
        game2.addElement("company").addText("马哥");
        //5.添加第三个game标签
        Element game3 = games.addElement("game");
        //添加属性
        game3.addAttribute("id", "3");
        //添加孙子标签
        game3.addElement("name").addText("CF");
        //添加孙子标签
        game3.addElement("company").addText("还是我马哥");

        //将文档对象写入到Game.xml文件中
        //1.创建解析对象
        OutputFormat prettyPrint = OutputFormat.createPrettyPrint();
        //2.创建流对象按格式写入
        prettyPrint.setEncoding("UTF-8");
        XMLWriter xmlWriter = new XMLWriter(new FileWriter("day14-code/src/xml/Game.xml"), prettyPrint);
        //3.写入
        xmlWriter.write(document);
        //4.关闭流
        xmlWriter.close();

    }
}
